#include "graphicslineitem.h"
#include "qline.h"
#include "qpen.h"
#include "draws.h"
#include "graphicsrectitem.h"
#include "maths.h"

GraphicsLineItem::GraphicsLineItem(QGraphicsItem *parent)
	: QGraphicsLineItem(parent)
{
	setFlags(QGraphicsItem::ItemIsMovable |
		QGraphicsItem::ItemIsSelectable);
	//QPointF p = QPointF(0,0);
	//QPointF px = QPointF(100,100);
	
	setPen(QPen(Qt::black, 1));//, Qt::DashLine));
	//setLine(QLineF( p , px));
}

GraphicsLineItem::~GraphicsLineItem()
{

}

void GraphicsLineItem::paint(QPainter *painter, 
	const QStyleOptionGraphicsItem *option, QWidget *widget)
{
	updateLine();

	QGraphicsLineItem::paint(painter,option,widget);

	//paintArrow(painter);
}

void GraphicsLineItem::paintArrow(QPainter * pt)
{
	// draw arrow;
	QLineF l = this->line();
	Draws::DrawArrow(pt,l.p1(),l.p2());
}
void GraphicsLineItem::connectItem(QGraphicsItem * item1, QGraphicsItem * item2)
{
	// >>todo: find cross-point of current line with item1 and item2;
	// then record the scale rate;

	// >>VUE: connect the center of two items;
	mItem1 = item1;
	mItem2 = item2;

	updateLine();
}
void GraphicsLineItem::updateLine()
{
	// call a line to connect centers of two items;
	QPointF p1 = mItem1->pos();
	QPointF p2 = mItem2->pos();

	QRectF rc1 = mItem1->boundingRect();
	QRectF rc2 = mItem2->boundingRect();
	
	rc1 = QRectF(p1.x(),p1.y(),rc1.width(),rc1.height());
	rc2 = QRectF(p2.x(),p2.y(),rc2.width(),rc2.height());

	p1.setX(p1.x() + rc1.width()/2);
	p1.setY(p1.y() + rc1.height()/2);

	p2.setX(p2.x() + rc2.width()/2);
	p2.setY(p2.y() + rc2.height()/2);

	QLineF line = QLineF(p1,p2);

	// call cross of center-line with item rect;	
	// >>todo: still wrong when items overlapped/contained;
	p1 = Maths::callCross(rc1,line);
	p2 = Maths::callCross(rc2, QLineF(p2,p1));

	setLine(QLineF(p1,p2));
}